package com.bbcare.followup.plat.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.entity.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.followup.plat.service.IFamilyReportService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IPatientFollowService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientqueryCardService;
import com.bbcare.followup.plat.service.IWeChatUserService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IFamilyReportDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;

/**
 * @name: 微信问卷评估
 * @author: DemonLee
 * @createTime: 2017.5.12
 * @description:
 * @modify:
 */
@Controller
@RequestMapping("/webapi/service/wechat")
public class WeChatUserController {
    private final Log logger = LogFactory.getLog(WeChatUserController.class);

    @Autowired
    IFamilyReportService familyReportService;

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

    @Autowired
    private IFollowEvaluationService followEvaluationService;

    @Autowired
    private IDepartmentBasicService deparmentBasicService;

    @Autowired
    IPatientDAO patientdao;

    @Autowired
    public IConfCacheDAO confCacheDao;

    @Autowired
    private IPatientTaskDAO patientTaskDao;

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    private IPatientqueryCardService patientqueryCardService;

    @Autowired
    private IWeChatUserService weChatUserService;

    @Autowired
    IFamilyReportDAO familyReportDAO;

    @Autowired
    private IPatientFollowService patientFollowService;



    /**
     * 建档和建档信息更新接口
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/updateArchives")
    public ResultModel<Map<String, Object>> updateArchives(@RequestBody String arg) throws Exception {
        logger.warn("in updateArchives----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String wechatCode = jsonData.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，wechatCode不能为空！"));
        }

        String deptCode = jsonData.getString("deptCode");// 科室二维码 编码
        String openId = jsonData.getString("openId");// 微信id
        String userId = jsonData.getString("userId");// 用户ID

        if (StringUtils.isBlank(deptCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，deptCode不能为空！"));
        }
        //根据openId 获取手机号
        if (StringUtils.isBlank(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，openId不能为空！"));
        }

        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        Map<String, Object> servParamMap = new HashMap<String, Object>();
        servParamMap.putAll(jsonData);

        String deptId = "";
        String tenantId = "";
        String queueId = "";

        //入参中没有，从问卷答案中获取
        Map<String, Object> quesMap = (JSONObject) jsonData.getJSONObject("questiones");
        JSONObject questiones = new JSONObject();

        String patientName = jsonData.getString("babyName");
        if (StringUtils.isBlank(patientName)) {
            if (null != quesMap && 0 != quesMap.size()) {
                patientName = (String) quesMap.get(Constants.QUESTION_ID_FOR_PATIENTNAME);
                if (StringUtils.isBlank(patientName)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "患者姓名不能为空！"));
                }
            }
        }
        if (!StringUtils.isEmpty(patientName)) {
            patientName = patientName.trim();
        }

        String gender = jsonData.getString("gender");
        if (StringUtils.isBlank(gender)) {
            if (null != quesMap && 0 != quesMap.size()) {
                gender = (String) quesMap.get(Constants.QUESTION_ID_FOR_GENDER);
                if (StringUtils.isBlank(gender)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "性别不能为空！"));
                }
            }
        }
        gender = gender.trim();
        // 转换性别
        if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender) || gender.startsWith(Constants.GENDER_ALIAS_FOR_MALE)) {
            gender = Constants.GENDER_FOR_MALE;
        } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender) || gender.startsWith(Constants.GENDER_ALIAS_FOR_FEMALE)) {
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        }

        String birthday = jsonData.getString("birthday");
        if (StringUtils.isBlank(birthday)) {
            if (null != quesMap && 0 != quesMap.size()) {
                birthday = (String) quesMap.get(Constants.QUESTION_ID_FOR_BIRTHDAY);
                if (StringUtils.isBlank(birthday)) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "出生日期不能为空！"));
                }
            }
        }

        String expectedDay = jsonData.getString("expectedDay");

        // 校验预产期是否传入
        Patient pt = new Patient();
        pt.setPregnancyDay(jsonData.getIntValue("pregnancyWeek"));
        if (0 == pt.getPregnancyDay() && !StringUtils.isBlank(expectedDay)) {
            // 根据生日和预产期计算孕周
            int pregnancyDay = ToolUtils.calPrenDayByBirthAndExpect(birthday, expectedDay);
            pt.setPregnancyDay(pregnancyDay);
        }

        if (StringUtils.isBlank(expectedDay)) {
            int day = Constants.PATIENT_NORMAL_PREGNANT_DAY - pt.getPregnancyDay();
            expectedDay = DateUtil.calcDay2(birthday, Constants.PLUS_CHAR, day);
        }

        //根据openId 查询手机号码
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("openId", openId);
        List<Map<String, Object>> list = confCacheDao.selectwechat(param);
        if (CollectionUtils.isEmpty(list)) {
            throw (new AppException(ErrorCode.EXCEPTION_WECHATID_NOT_BIND_PHONENUM, "微信号还没有绑定手机号码"));
        }
        String phoneNum = (String) list.get(0).get("phone_no");

        param.clear();
        param.put("code", deptCode);
        param.put("queueUsertype", Constants.QUEUE_USER_TYPE_BABY);
        param.put("optionStatus", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        param.put("wechatCode", wechatCode);
        Map<String, Object> map = confCacheDao.selectDeptAndQueueIdByCode(param);
        if (null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码"));
        }
        queueId = (String) map.get("queueId");
        deptId = (String) map.get("deptId");
        tenantId = (String) map.get("tenantId");
        String queueName = (String) map.get("queueName");

        String bfStuation = jsonData.getString("bfStuation");
        String brotherBirthday = jsonData.getString("brotherBirthday");
        String brotherBirthday1 = jsonData.getString("brotherBirthday1");
        String brotherBirthday2 = jsonData.getString("brotherBirthday2");
        String fatherEducation = jsonData.getString("fatherEducation");
        String fatherProfession = jsonData.getString("fatherProfession");
        String hasBrother = jsonData.getString("hasBrother");
        String hasSister = jsonData.getString("hasSister");
        String hospitalName = jsonData.getString("hospitalName");
        String isHospitalName = jsonData.getString("isHospitalName");
        String motherBirthday = jsonData.getString("motherBirthday");
        String motherEducation = jsonData.getString("motherEducation");
        String motherIdCard = jsonData.getString("motherIdCard");
        String motherName = jsonData.getString("motherName");
        String motherProfession = jsonData.getString("motherProfession");
        String secondhandSmoke = jsonData.getString("secondhandSmoke");
        String sisterBirthday = jsonData.getString("sisterBirthday");
        String sisterBirthday1 = jsonData.getString("sisterBirthday1");
        String sisterBirthday2 = jsonData.getString("sisterBirthday2");
        String smoking = jsonData.getString("smoking");
        if ("0".equals(bfStuation)) {
            questiones.put("Lehui000003", "纯母乳喂养");
        } else if ("1".equals(bfStuation)) {
            questiones.put("Lehui000003", "混合喂养");
        } else if ("2".equals(bfStuation)) {
            questiones.put("Lehui000003", "人工喂养");
        }
        questiones.put("Lehui000018", brotherBirthday1);
        questiones.put("Lehui000019", brotherBirthday2);
        questiones.put("Lehui000022", brotherBirthday);

        if ("0".equals(hasBrother)) {
            questiones.put("Lehui000012", "无");
        } else if ("1".equals(hasBrother)) {
            questiones.put("Lehui000012", "1个");
        } else if ("2".equals(hasBrother)) {
            questiones.put("Lehui000012", "2个");
        }

        if ("0".equals(hasSister)) {
            questiones.put("Lehui000013", "无");
        } else if ("1".equals(hasSister)) {
            questiones.put("Lehui000013", "1个");
        } else if ("2".equals(hasSister)) {
            questiones.put("Lehui000013", "2个");
        }

        questiones.put("Lehui000011", fatherProfession);
        questiones.put("Lehui000004", motherName);
        if ("0".equals(motherEducation)) {
            questiones.put("Lehui000008", "小学及以下");
        } else if ("1".equals(motherEducation)) {
            questiones.put("Lehui000008", "中学");
        } else if ("2".equals(motherEducation)) {
            questiones.put("Lehui000008", "大学及以上");
        }
        if ("0".equals(fatherEducation)) {
            questiones.put("Lehui000009", "小学及以下");
        } else if ("1".equals(fatherEducation)) {
            questiones.put("Lehui000009", "中学");
        } else if ("2".equals(fatherEducation)) {
            questiones.put("Lehui000009", "大学及以上");
        }
        questiones.put("Lehui000001", motherIdCard);
        questiones.put("Lehui000010", motherProfession);
        questiones.put("Lehui000024", sisterBirthday);
        questiones.put("Lehui000023", sisterBirthday1);
        questiones.put("Lehui000026", sisterBirthday2);
        if ("0".equals(smoking)) {
            questiones.put("Lehui000006", "否");
        } else if ("1".equals(smoking)) {
            questiones.put("Lehui000006", "偶尔");
        } else if ("2".equals(smoking)) {
            questiones.put("Lehui000006", "经常");
        }
        if ("0".equals(secondhandSmoke)) {
            questiones.put("Lehui000007", "否");
        } else if ("1".equals(secondhandSmoke)) {
            questiones.put("Lehui000007", "偶尔");
        } else if ("2".equals(secondhandSmoke)) {
            questiones.put("Lehui000007", "经常");
        }
        questiones.put("Lehui000005", motherBirthday);
        if (pt.getPregnancyDay() > 0) {
            int day = pt.getPregnancyDay();
            int week = day / 7;
            int remain = day % 7;
            JSONArray json = new JSONArray();
            json.add(week);
            json.add(remain);
            questiones.put("Lehui000002", json.toJSONString());
        }

        if ("1".equals(isHospitalName)) {
            questiones.put("Lehui000029", "本院");
        } else if ("2".equals(isHospitalName)) {
            questiones.put("Lehui000029", "非本院");
        }
        questiones.put("Lehui000028", hospitalName);

        questiones.put(Constants.QUESTION_ID_FOR_PHONENO, phoneNum);
        questiones.put(Constants.QUESTION_ID_FOR_PATIENTNAME, patientName);
        questiones.put(Constants.QUESTION_ID_FOR_EXPECTEDDAY, expectedDay);
        if ("N".equals(gender)) {
            questiones.put(Constants.QUESTION_ID_FOR_GENDER, "男孩");
        } else if ("F".equals(gender)) {
            questiones.put(Constants.QUESTION_ID_FOR_GENDER, "女孩");
        }

        questiones.put(Constants.QUESTION_ID_FOR_BIRTHDAY, birthday);

        String opCode = Constants.OP_CODE_1000;
        String opType = "4"; //自助
        String opNode = "患者【" + patientName + "】通过微信建档，加入队列" + queueName;

        pt.setUserName(patientName);
        pt.setPhoneNo(phoneNum);
        pt.setFirstName(patientName.substring(0, 1));
        pt.setCreateTime(currTime);
        pt.setUpdateTime(currTime);
        pt.setCreateAuthor("微信端");
        pt.setBirthday(birthday);
        pt.setExpectedDay(expectedDay);
        pt.setGender(gender);
        pt.setUserType("1");
        pt.setSourceType("4"); //乐慧微信自助建档
        pt.setWechat_id(openId);

        servParamMap.put("babyName", patientName);
        servParamMap.put("openId", openId);
        servParamMap.put("phoneNum", phoneNum);

        servParamMap.put("patient", pt);
        servParamMap.put("authorName", patientName);
        servParamMap.put("deptId", deptId);
        servParamMap.put("queueId", queueId);
        servParamMap.put("updateTime", currTime);
        servParamMap.put("authorId", "乐慧微信端");
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("tenantId", tenantId);
        servParamMap.put("opCode", opCode);
        servParamMap.put("opNote", opNode);
        servParamMap.put("opType", opType);
        servParamMap.put("contentData", questiones);
        servParamMap.put("userType", "1");
        logger.info("乐慧微信建档：" + servParamMap.toString());

        //先根据微信号 租户下是否建过用户
        Map<String, Object> qryPtMap = new HashMap<String, Object>();
        qryPtMap.put("phoneNo", phoneNum);
//		qryPtMap.put("wechat_id",openId);
//		qryPtMap.put("userName",patientName);
        qryPtMap.put("tenantId", tenantId);
        qryPtMap.put("userType", "1");
        List<Patient> ptList = patientdao.selectByPhoneNo(qryPtMap);

        //根据科室ID 查询租户ID
        Map<String, Object> ptMap = new HashMap<String, Object>();
        if (!CollectionUtils.isEmpty(ptList)) {
            userId = ptList.get(0).getId();
        }
        ptMap.put("userId", userId);
        ptMap.put("tenantId", tenantId);
        ptMap.put("queueId", queueId);
        List<String> statulist = new ArrayList<String>();
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        ptMap.put("status", statulist);

        List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
        String ptSchemeId = "";
        Map<String, Object> userMap = null;
        if (CollectionUtils.isEmpty(queueSchemeList)) {
            //一个微信号 对应一个租户下的用户
            if (!CollectionUtils.isEmpty(ptList)) {
                servParamMap.put("patientOld", ptList.get(0));
            }
            userMap = weChatUserService.wechatRegister(servParamMap);
            ptSchemeId = (String) userMap.get("ptSchemeId");
            userId = (String) userMap.get("patientId");
        } else {
            //更新建档信息
            ptSchemeId = queueSchemeList.get(0).getId();
            ptMap.clear();
            ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
            ptMap.put("ptSchemeId", ptSchemeId);
            // 查询taskid
            List<PatientTask> taskList = patientTaskDao.select(ptMap);
            String taskId = "";
            if (!CollectionUtils.isEmpty(taskList)) {
                taskId = taskList.get(0).getId();
            }

            servParamMap.put("ptSchemeId", ptSchemeId);
            servParamMap.put("userId", userId);
            servParamMap.put("taskId", taskId);
            servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
            patientService.modTaskContentData(servParamMap);

        }
        jsonData.put("userId", userId);
        jsonData.put("queueId", queueId);
        jsonData.put("deptId", deptId);
        jsonData.put("ptSchemeId", ptSchemeId);
        return new ResultModel<Map<String, Object>>(jsonData);
    }


    /**
     * 乐慧产妇建档 接口
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/maternalArchives")
    public ResultModel<Map<String, Object>> maternalArchives(@RequestBody String arg) throws Exception {
        logger.warn("in maternalArchives----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String wechatCode = jsonData.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode不能为空！"));
        }

        String deptCode = jsonData.getString("deptCode");// 科室二维码 编码
        String openId = jsonData.getString("openId");// 微信id
        String phoneNum = jsonData.getString("phoneNum");// 微信id
        if (StringUtils.isBlank(deptCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，deptCode不能为空！"));
        }
        //根据openId 获取手机号
        if (StringUtils.isBlank(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，openId不能为空！"));
        }

        //手机号不能为空
        if (StringUtils.isBlank(phoneNum)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，phoneNum不能为空！"));
        }

        String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
        String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

        Map<String, Object> servParamMap = new HashMap<String, Object>();
        servParamMap.putAll(jsonData);

        String deptId = "";
        String tenantId = "";
        String queueId = "";

        JSONObject questiones = new JSONObject();
        String patientName = jsonData.getString("userName");
        //姓名不能为空
        if (StringUtils.isBlank(patientName)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，母亲姓名不能为空！"));
        }
        patientName = patientName.trim();

        String gender = Constants.GENDER_FOR_FEMALE;//性别女
        // 转换性别
        if (Constants.GENDER_ALIAS_FOR_MALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        } else if (Constants.GENDER_ALIAS_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_FEMALE;
        } else if (!Constants.GENDER_FOR_MALE.equals(gender) && !Constants.GENDER_FOR_FEMALE.equals(gender)) {
            gender = Constants.GENDER_FOR_MALE;
        }

        String babyBirthDay = jsonData.getString("babyBirthDay");//报文
        //宝宝生日不能为空
        /*if(StringUtils.isBlank(babyBirthDay)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，宝宝生日不能为空！"));
		}*/

        String pregnancyWeekStr = jsonData.getString("pregnancyWeek");//报文
        //母亲孕周不能为空
        if (!ToolUtils.isNumeric(pregnancyWeekStr)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，孕周不能为空且必须为数字！"));
        }

        int pregnancyWeek = jsonData.getIntValue("pregnancyWeek");
        // 校验预产期是否传入
        Patient pt = new Patient();
        pt.setPregnancyDay(pregnancyWeek);

        //根据openId 查询手机号码
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("code", deptCode);
        param.put("queueUsertype", Constants.QUEUE_USER_TYPE_PARTURIENT);//队列类型  母亲
        param.put("optionStatus", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        param.put("wechatCode", wechatCode);
        Map<String, Object> map = confCacheDao.selectDeptAndQueueIdByCode(param); //
        if (null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码"));
        }

        queueId = (String) map.get("queueId");
        deptId = (String) map.get("deptId");
        tenantId = (String) map.get("tenantId");
        String queueName = (String) map.get("queueName");

        String motherIdCard = jsonData.getString("motherIdCard");
        questiones.put(Constants.QUESTION_ID_FOR_PHONENO, phoneNum);
        questiones.put(Constants.QUESTION_ID_FOR_PATIENTNAME, patientName);

        questiones.put("Lehui000001", motherIdCard);
        questiones.put("Lehui0100001", babyBirthDay);
        questiones.put(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK, pregnancyWeekStr);
        if ("N".equals(gender)) {
            questiones.put(Constants.QUESTION_ID_FOR_GENDER, "男孩");
        } else if ("F".equals(gender)) {
            questiones.put(Constants.QUESTION_ID_FOR_GENDER, "女孩");
        }

        String opCode = Constants.OP_CODE_1000;
        String opType = "4"; //自助
        String opNode = "患者【" + patientName + "】通过微信建档，加入队列" + queueName;

        pt.setUserName(patientName);
        pt.setPhoneNo(phoneNum);
        pt.setFirstName(patientName.substring(0, 1));
        pt.setCreateTime(currTime);
        pt.setUpdateTime(currTime);
        pt.setCreateAuthor("微信端");
        pt.setGender(gender);
        pt.setUserType("2");
        pt.setSourceType("4"); //乐慧微信自助建档
        pt.setWechat_id(openId);

        servParamMap.put("babyName", patientName);
        servParamMap.put("openId", openId);
        servParamMap.put("phoneNum", phoneNum);
        servParamMap.put("patient", pt);
        servParamMap.put("authorName", patientName);
        servParamMap.put("deptId", deptId);
        servParamMap.put("queueId", queueId);
        servParamMap.put("updateTime", currTime);
        servParamMap.put("authorId", "乐慧微信端");
        servParamMap.put("updateAccept", updateAccept);
        servParamMap.put("tenantId", tenantId);
        servParamMap.put("opCode", opCode);
        servParamMap.put("opNote", opNode);
        servParamMap.put("opType", opType);
        servParamMap.put("contentData", questiones);
        servParamMap.put("userType", pt.getUserType());
        logger.info("乐慧微信母乳喂养建档：" + servParamMap.toString());

        //先根据微信号 租户下是否建过用户
        Map<String, Object> qryPtMap = new HashMap<String, Object>();
        qryPtMap.put("phoneNo", phoneNum);
//		qryPtMap.put("wechat_id", openId);
        qryPtMap.put("tenantId", tenantId);
        qryPtMap.put("userType", "2");
        List<Patient> ptList = patientdao.selectByPhoneNo(qryPtMap);

        String userId = "";
        Map<String, Object> ptMap = new HashMap<String, Object>();
        if (!CollectionUtils.isEmpty(ptList)) {
            userId = ptList.get(0).getId();
        }
        ptMap.put("userId", userId);
        ptMap.put("tenantId", tenantId);
        ptMap.put("queueId", queueId);
        List<String> statulist = new ArrayList<String>();
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        ptMap.put("status", statulist);
        List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
        String ptSchemeId = "";
        Map<String, Object> userMap = null;
        if (CollectionUtils.isEmpty(queueSchemeList)) {
            //一个微信号 对应一个租户下的一个类型的用户信息  ---产妇或宝宝
            userMap = weChatUserService.wechatRegister(servParamMap);
            ptSchemeId = (String) userMap.get("ptSchemeId");
            userId = (String) userMap.get("patientId");
        } else {
            //更新建档信息
            ptSchemeId = queueSchemeList.get(0).getId();
            ptMap.clear();
            ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
            ptMap.put("ptSchemeId", ptSchemeId);
            // 查询taskid
            List<PatientTask> taskList = patientTaskDao.select(ptMap);
            String taskId = "";
            if (!CollectionUtils.isEmpty(taskList)) {
                taskId = taskList.get(0).getId();
            }

            servParamMap.put("ptSchemeId", ptSchemeId);
            servParamMap.put("userId", userId);
            servParamMap.put("taskId", taskId);
            servParamMap.put("type", Constants.QUESTIONNAIRE_TYPE_0);
            patientService.modTaskContentData(servParamMap);

        }
        jsonData.put("userId", userId);
        jsonData.put("queueId", queueId);
        jsonData.put("deptId", deptId);
        jsonData.put("ptSchemeId", ptSchemeId);
        return new ResultModel<Map<String, Object>>(jsonData);
    }

    /**
     * 手机号微信绑定接口
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/wechatBind")
    public ResultModel<Map<String, Object>> wechatBind(@RequestBody String arg) throws Exception {
        logger.warn("in wechatBind----arg==" + arg.toString());

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String openId = jsonData.getString("openId");
        if (StringUtils.isEmpty(openId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "openId不能为空!");
        }

        String phoneNum = jsonData.getString("phoneNum");
        if (StringUtils.isEmpty(phoneNum)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号不能为空");
        }

        String verifyCode = jsonData.getString("verifyCode");
        if (StringUtils.isEmpty(verifyCode)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "验证码不能为空");
        }

        //checkVerifyCode
        int flag = patientqueryCardService.checkVerifyCodeLh(phoneNum, verifyCode, "01", "1", openId);
        if (flag == 1) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "尊敬的用户，您的验证码已经失效，请重新获取！");
        }

        return new ResultModel<Map<String, Object>>(null);
    }

    /**
     * 建档信息查询
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/getArchives")
    public ResultModel<Map<String, Object>> getArchives(@RequestBody String arg) throws Exception {
        logger.warn("in getArchives----arg==" + arg.toString());
        //openId code 查询
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String wechatCode = jsonData.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode不能为空！"));
        }

        String deptCode = jsonData.getString("deptCode");// 科室二维码 编码
        String openId = jsonData.getString("openId");// 微信id

        if (StringUtils.isBlank(deptCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，deptCode不能为空！"));
        }
        //根据openId 获取手机号
        if (StringUtils.isBlank(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，openId不能为空！"));
        }

        //根据openId 查询手机号码
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("openId", openId);
        List<Map<String, Object>> list = confCacheDao.selectwechat(param);
        if (CollectionUtils.isEmpty(list) || org.springframework.util.StringUtils.isEmpty(list.get(0).get("phone_no"))) {
            throw (new AppException(ErrorCode.EXCEPTION_WECHATID_NOT_BIND_PHONENUM, "微信号还没有绑定手机号码"));
        }
        String phoneNum = (String) list.get(0).get("phone_no");

        param.clear();
        param.put("code", deptCode);
        param.put("queueUsertype", Constants.QUEUE_USER_TYPE_BABY);//队列类型  母亲
        param.put("optionStatus", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        param.put("wechatCode", wechatCode);
        Map<String, Object> map = confCacheDao.selectDeptAndQueueIdByCode(param);
        if (null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码"));
        }

        String queueId = (String) map.get("queueId");
        String deptId = (String) map.get("deptId");
        String tenantId = (String) map.get("tenantId");
//		String queueName =  (String)map.get("queueName");

        //根据手机号 和租户 查询用户上个科室基本信息  //没有则跳转建档
        Map<String, Object> qryPtMap = new HashMap<String, Object>();
        qryPtMap.put("phoneNo", phoneNum);
//        qryPtMap.put("wechat_id", openId);
        qryPtMap.put("tenantId", tenantId);
        qryPtMap.put("userType", Constants.PTUSER_PATIENT_USER_TYPE_BABY);
        List<Patient> ptList = patientdao.selectByPhoneNo(qryPtMap);
        if (CollectionUtils.isEmpty(ptList)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者记录不存在,请建档"));
        }

        String uesrId = ptList.get(0).getId();
        //先查看 是否加入该租户队列
        Map<String, Object> ptMap = new HashMap<String, Object>();
        ptMap.put("userId", uesrId);
        ptMap.put("tenantId", tenantId);
        ptMap.put("queueId", queueId);
        List<String> statulist = new ArrayList<String>();
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        ptMap.put("status", statulist);
        List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);

        String ptSchemeId = "";
        String userId = "";
        JSONObject questiones = new JSONObject();
        if (CollectionUtils.isEmpty(queueSchemeList)) {
            //先简单做 新的队列 跳建档页面 重新建档
			/*//如果多中心 多队列都有该用户  则取租户下 最近一个用户 建档资料 加入该队列中
			ptMap.clear();
			ptMap.put("userId",uesrId);
			ptMap.put("tenantId",tenantId);
//			ptMap.put("queueId",queueId);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
			ptMap.put("status", statulist);
			List<PatientQueueScheme> queueSchemeListTemp= patientQueueSchemeDao.selectByUserId(ptMap);
			if(CollectionUtils.isEmpty(queueSchemeListTemp)){
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者记录不存在,请建档"));
			}else{
				ptSchemeId =  queueSchemeListTemp.get(0).getId();
			}

			ptMap.clear();
			ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
			ptMap.put("ptSchemeId",ptSchemeId);
			// 查询taskid
			List<PatientTask> taskList = patientTaskDao.select(ptMap);
			String taskId ="";
			if (!CollectionUtils.isEmpty(taskList)) {
				taskId = taskList.get(0).getId();
			}

	        ptMap.put("tenantId", tenantId);
	        ptMap.put("groupType", Constants.TENANT_GROUP_TYPE_FOR_MULCENTER);
	        ptMap.put("rootGroupId", deptId);
	        if (null == queueId || "".equals(queueId)) {
	            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
	        }
	        ptMap.put("taskId", taskId);
	        ptMap.put("queueId", queueId);
	        Map<String, Object> retMap = patientService.qryPatientContentList(ptMap);

	        if(null != retMap){
	        	String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
	    		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水

	    		String opCode = Constants.OP_CODE_1000;
	    		String opType = "4"; //自助
	    		String opNode ="患者【"+ptList.get(0).getUserName()+"】通过微信同步用户信息，加入队列"+queueName;

	        	Map<String, Object> servParamMap = new HashMap<String, Object>();
	        	servParamMap.put("patient", ptList.get(0));
	    		servParamMap.put("authorName",ptList.get(0).getUserName());
	    		servParamMap.put("deptId", deptId);
	    		servParamMap.put("queueId", queueId);
	    		servParamMap.put("updateTime", currTime);
	    		servParamMap.put("authorId", "乐慧微信端");
	    		servParamMap.put("updateAccept",updateAccept);
	    		servParamMap.put("tenantId", tenantId);
	    		servParamMap.put("opCode", opCode);
	    		servParamMap.put("opNote", opNode);
	    		servParamMap.put("opType", opType);
	    		questiones = JSONObject.parseObject(retMap.get("values").toString());
	    		servParamMap.put("contentData", questiones);
	    		patientService.registerPatient(servParamMap);
	        }*/
        } else {
            ptSchemeId = queueSchemeList.get(0).getId();
            userId = queueSchemeList.get(0).getUserId();
            ptMap.clear();
            ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
            ptMap.put("ptSchemeId", ptSchemeId);
            // 查询taskid
            List<PatientTask> taskList = patientTaskDao.select(ptMap);
            String taskId = "";
            if (!CollectionUtils.isEmpty(taskList)) {
                taskId = taskList.get(0).getId();
            }

            ptMap.put("tenantId", tenantId);
            ptMap.put("groupType", Constants.TENANT_GROUP_TYPE_FOR_MULCENTER);
            ptMap.put("rootGroupId", deptId);
            if (null == queueId || "".equals(queueId)) {
                throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，未传入队列id或值为空！"));
            }
            ptMap.put("taskId", taskId);
            ptMap.put("queueId", queueId);
            Map<String, Object> retMap = patientService.qryPatientContentList(ptMap);
//	        System.out.println(retMap.get("values").toString());
            questiones = JSONObject.parseObject(JSON.toJSONString(retMap.get("values")));
        }

        //返回建档信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        if (null != questiones) {
            if ("纯母乳喂养".equals(questiones.get("Lehui000003"))) {
                rspMap.put("bfStuation", "0");
            } else if ("混合喂养".equals(questiones.get("Lehui000003"))) {
                rspMap.put("bfStuation", "1");
            } else if ("人工喂养".equals(questiones.get("Lehui000003"))) {
                rspMap.put("bfStuation", "2");
            }

            rspMap.put("brotherBirthday1", questiones.get("Lehui000018"));
            rspMap.put("brotherBirthday2", questiones.get("Lehui000019"));
            rspMap.put("brotherBirthday", questiones.get("Lehui000022"));

            if ("无".equals(questiones.get("Lehui000012"))) {
                rspMap.put("hasBrother", "0");
            } else if ("1个".equals(questiones.get("Lehui000012"))) {
                rspMap.put("hasBrother", "1");
            } else if ("2个".equals(questiones.get("Lehui000012"))) {
                rspMap.put("hasBrother", "2");
            }

            if ("无".equals(questiones.get("Lehui000013"))) {
                rspMap.put("hasSister", "0");
            } else if ("1个".equals(questiones.get("Lehui000013"))) {
                rspMap.put("hasSister", "1");
            } else if ("2个".equals(questiones.get("Lehui000013"))) {
                rspMap.put("hasSister", "2");
            }

            rspMap.put("fatherProfession", questiones.get("Lehui000011"));
            rspMap.put("motherName", questiones.get("Lehui000004"));
            if ("小学及以下".equals(questiones.get("Lehui000008"))) {
                rspMap.put("motherEducation", "0");
            } else if ("中学".equals(questiones.get("Lehui000008"))) {
                rspMap.put("motherEducation", "1");
            } else if ("大学及以上".equals(questiones.get("Lehui000008"))) {
                rspMap.put("motherEducation", "2");
            }

            if ("小学及以下".equals(questiones.get("Lehui000009"))) {
                rspMap.put("fatherEducation", "0");
            } else if ("中学".equals(questiones.get("Lehui000009"))) {
                rspMap.put("fatherEducation", "1");
            } else if ("大学及以上".equals(questiones.get("Lehui000009"))) {
                rspMap.put("fatherEducation", "2");
            }
            rspMap.put("motherIdCard", questiones.get("Lehui000001"));
            rspMap.put("motherProfession", questiones.get("Lehui000010"));
            rspMap.put("sisterBirthday", questiones.get("Lehui000024"));
            rspMap.put("sisterBirthday1", questiones.get("Lehui000023"));
            rspMap.put("sisterBirthday2", questiones.get("Lehui000026"));
            if ("否".equals(questiones.get("Lehui000006"))) {
                rspMap.put("smoking", "0");
            } else if ("偶尔".equals(questiones.get("Lehui000006"))) {
                rspMap.put("smoking", "1");
            } else if ("经常".equals(questiones.get("Lehui000006"))) {
                rspMap.put("smoking", "2");
            }
            if ("否".equals(questiones.get("Lehui000007"))) {
                rspMap.put("secondhandSmoke", "0");
            } else if ("偶尔".equals(questiones.get("Lehui000007"))) {
                rspMap.put("secondhandSmoke", "1");
            } else if ("经常".equals(questiones.get("Lehui000007"))) {
                rspMap.put("secondhandSmoke", "2");
            }
            rspMap.put("motherBirthday", questiones.get("Lehui000005"));

            if (null != questiones.get("Lehui000002")) {
                JSONArray arr = JSONArray.parseArray(questiones.get("Lehui000002").toString());
                int pregnancyWeek = 0;
                if (arr.size() == 2) {
                    pregnancyWeek = arr.getIntValue(0) * 7 + arr.getIntValue(1);
                }
                rspMap.put("pregnancyWeek", pregnancyWeek);
            }

            if ("本院".equals(questiones.get("Lehui000029"))) {
                rspMap.put("isHospitalName", "1");
            } else if ("非本院".equals(questiones.get("Lehui000029"))) {
                rspMap.put("isHospitalName", "2");
            }
            rspMap.put("hospitalName", questiones.get("Lehui000028"));
//			rspMap.put("",questiones.get(Constants.QUESTION_ID_FOR_PHONENO));
            rspMap.put("babyName", questiones.get(Constants.QUESTION_ID_FOR_PATIENTNAME));

            if ("男孩".equals(questiones.get(Constants.QUESTION_ID_FOR_GENDER))) {
                rspMap.put("gender", "N");
            } else if ("女孩".equals(questiones.get(Constants.QUESTION_ID_FOR_GENDER))) {
                rspMap.put("gender", "F");
            }
            rspMap.put("birthday", questiones.get(Constants.QUESTION_ID_FOR_BIRTHDAY));
            rspMap.put("userId", userId);
            rspMap.put("queueId", queueId);
            rspMap.put("deptId", deptId);
        }

        return new ResultModel<Map<String, Object>>(rspMap);
    }

    /**
     * 孕妇建档信息查询
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/qryMaternalInfo")
    public ResultModel<Map<String, Object>> getMaternalInfo(@RequestBody String arg) throws Exception {
        logger.warn("in getMaternalInfo----arg==" + arg.toString());
        //openId code 查询
        Map<String, Object> rspMap = new HashMap<String, Object>();
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String wechatCode = jsonData.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode不能为空！"));
        }

        String deptCode = jsonData.getString("deptCode");// 科室二维码 编码
        String openId = jsonData.getString("openId");// 微信id

        if (StringUtils.isBlank(deptCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，deptCode不能为空！"));
        }
        //根据openId 获取手机号
        if (StringUtils.isBlank(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，openId不能为空！"));
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("code", deptCode);
        param.put("queueUsertype", Constants.QUEUE_USER_TYPE_PARTURIENT);
        param.put("optionStatus", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        param.put("wechatCode", wechatCode);
        Map<String, Object> map = confCacheDao.selectDeptAndQueueIdByCode(param);
        if (null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码"));
        }

        String queueId = (String) map.get("queueId");
        String deptId = (String) map.get("deptId");
        String tenantId = (String) map.get("tenantId");

        //根据openId 查询手机号码
        Map<String, Object> param1 = new HashMap<String, Object>();
        param1.put("openId", openId);
        List<Map<String, Object>> list = confCacheDao.selectwechat(param1);

        if (CollectionUtils.isEmpty(list) || org.springframework.util.StringUtils.isEmpty(list.get(0).get("phone_no"))) {
            rspMap.put("type", "00");
            return new ResultModel<Map<String, Object>>(rspMap);
        }

        //根据微信号 	 查询用户上个科室基本信息  //没有则跳转建档
        Map<String, Object> qryPtMap = new HashMap<String, Object>();
        String phoneNum = (String) list.get(0).get("phone_no");
        qryPtMap.put("phoneNo", phoneNum);
        qryPtMap.put("wechat_id", openId);
        qryPtMap.put("tenantId", tenantId);
        qryPtMap.put("userType", "2");
        List<Patient> ptList = patientdao.selectByWechatId(qryPtMap);
        if (CollectionUtils.isEmpty(ptList)) {
            rspMap.put("type", "02");
            rspMap.put("phoneNum", phoneNum);
        } else {
            Patient pt = ptList.get(0);
            String userId = pt.getId();
            //先查看 是否加入该租户队列
            Map<String, Object> ptMap = new HashMap<String, Object>();
            ptMap.put("userId", userId);
            ptMap.put("tenantId", tenantId);
            ptMap.put("queueId", queueId);
            List<String> statulist = new ArrayList<String>();
            statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
            ptMap.put("status", statulist);
            List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);

            String ptSchemeId = "";
            JSONObject questiones = new JSONObject();
            if (CollectionUtils.isEmpty(queueSchemeList)) {
                rspMap.put("type", "02");
                rspMap.put("phoneNum", phoneNum);
                return new ResultModel<Map<String, Object>>(rspMap);
            } else {
                ptSchemeId = queueSchemeList.get(0).getId();
                userId = queueSchemeList.get(0).getUserId();
                ptMap.clear();
                ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
                ptMap.put("ptSchemeId", ptSchemeId);
                // 查询taskid
                List<PatientTask> taskList = patientTaskDao.select(ptMap);
                String taskId = "";
                if (!CollectionUtils.isEmpty(taskList)) {
                    taskId = taskList.get(0).getId();
                }
                ptMap.put("tenantId", tenantId);
                ptMap.put("groupType", Constants.TENANT_GROUP_TYPE_FOR_MULCENTER);
                ptMap.put("rootGroupId", deptId);
                ptMap.put("taskId", taskId);
                ptMap.put("queueId", queueId);
                Map<String, Object> retMap = patientService.qryPatientContentList(ptMap);
                questiones = JSONObject.parseObject(JSON.toJSONString(retMap.get("values")));

                rspMap.put("phoneNum", pt.getPhoneNo());
                rspMap.put("userName", pt.getUserName());
                rspMap.put("type", "01");
                rspMap.put("userId", userId);
                rspMap.put("queueId", queueId);
                rspMap.put("deptId", deptId);
                if (null != questiones) {
                    rspMap.put("motherIdCard", questiones.get("Lehui000001"));
                    rspMap.put("babyBirthDay", questiones.get("Lehui0100001"));
                    rspMap.put("pregnancyWeek", questiones.get(Constants.QUESTION_ID_FOR_PREGNANCY_FIRST_WEEK));
                }
            }
        }
        return new ResultModel<Map<String, Object>>(rspMap);
    }


    /**
     * 中转页面接口
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/toview")
    public ResultModel<Map<String, Object>> toview(@RequestBody String arg) throws Exception {
        logger.warn("in toview----arg==" + arg.toString());
        //openId code 查询
        Map<String, Object> rspMap = new HashMap<String, Object>();
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String wechatCode = jsonData.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode不能为空！"));
        }

        String deptCode = jsonData.getString("deptCode");// 科室二维码 编码
        String openId = jsonData.getString("openId");// 微信id

        if (StringUtils.isBlank(deptCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，deptCode不能为空！"));
        }
        //根据openId 获取手机号
        if (StringUtils.isBlank(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，openId不能为空！"));
        }

        String type = "";
        //已经建档 加入同租户下其他队列 ， 将宝宝也加入新的队列 --同步
        //根据openId 查询手机号码
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("openId", openId);
        List<Map<String, Object>> list = confCacheDao.selectwechat(param);
        if (CollectionUtils.isEmpty(list) || org.springframework.util.StringUtils.isEmpty(list.get(0).get("phone_no"))) {
            type = "00";
            rspMap.put("type", type);
            return new ResultModel<Map<String, Object>>(rspMap);
        }
        String phoneNum = (String) list.get(0).get("phone_no");

        param.clear();
        param.put("code", deptCode);
        param.put("queueUsertype", Constants.QUEUE_USER_TYPE_BABY);
        param.put("optionStatus", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        param.put("wechatCode", wechatCode);
        Map<String, Object> map = confCacheDao.selectDeptAndQueueIdByCode(param);
        if (null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码"));
        }

        String queueId = (String) map.get("queueId");
        String tenantId = (String) map.get("tenantId");
//		String queueName =  (String)map.get("queueName");
        String deptId = (String) map.get("deptId");

        //根据手机号 和租户 查询用户上个科室基本信息  //没有则跳转建档
        Map<String, Object> qryPtMap = new HashMap<String, Object>();
        qryPtMap.put("phoneNo", phoneNum);
//        qryPtMap.put("wechat_id", openId);
        qryPtMap.put("tenantId", tenantId);
        qryPtMap.put("userType", "1");
        List<Patient> ptList = patientdao.selectByPhoneNo(qryPtMap);
        if (CollectionUtils.isEmpty(ptList)) {
            type = "01";
            rspMap.put("type", type);
            return new ResultModel<Map<String, Object>>(rspMap);
        } else {
            if (null == ptList.get(0).getBirthday()) {
                type = "02";
                rspMap.put("type", type);
                return new ResultModel<Map<String, Object>>(rspMap);
            }
        }

        String uesrId = ptList.get(0).getId();
        //先查看 是否加入该租户队列
        Map<String, Object> ptMap = new HashMap<String, Object>();
        ptMap.put("userId", uesrId);
        ptMap.put("tenantId", tenantId);
        ptMap.put("queueId", queueId);
        List<String> statulist = new ArrayList<String>();
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        ptMap.put("status", statulist);
        List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);

        if (CollectionUtils.isEmpty(queueSchemeList)) {
            type = "03";
            rspMap.put("type", type);
            return new ResultModel<Map<String, Object>>(rspMap);
        }

        type = "04";
        rspMap.put("type", type);
        rspMap.put("deptId", deptId);
        rspMap.put("userId", queueSchemeList.get(0).getUserId());
        rspMap.put("queueId", queueSchemeList.get(0).getQueueId());
        return new ResultModel<Map<String, Object>>(rspMap);
    }


    /**
     * 基本信息查询
     *
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/patientquery")
    public ResultModel<Map<String, Object>> patientquery(@RequestBody String arg) throws Exception {
        logger.warn("in patientquery----arg==" + arg.toString());
        //openId code 查询
        Map<String, Object> rspMap = new HashMap<String, Object>();
        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }
        String code = jsonData.getString("code");
        String openId = jsonData.getString("openId");// 微信id
        if (StringUtils.isBlank(code) && StringUtils.isBlank(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，授权码code和openId不能都为空！"));
        }

        String wechatCode = jsonData.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode不能为空！"));
        }

        String deptCode = "";
        //如果openId 不为空  根据openId 获取手机号
        if (StringUtils.isEmpty(openId)) {
            openId = ToolUtils.getOpenId(code); //openId 未传入 则根据code获取openId
        }

        String appid = "";
        String secret = "";
        String redisKey = "";
        if (Constants.WECHAT_CHANNEL_LH.equals(wechatCode)) {
            appid = PropertiesUtils.getProperty("appid_lhn");
            secret = PropertiesUtils.getProperty("secret_lhn");
            redisKey = Constants.ACCESS_TOKEN_LEHUI;
        } else if (Constants.WECHAT_CHANNEL_EB.equals(wechatCode)) {
            appid = PropertiesUtils.getProperty("appid_ebsf");
            secret = PropertiesUtils.getProperty("secret_ebsf");
            redisKey = Constants.ACCESS_TOKEN_EBSF;
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode值不正确！"));
        }

		/*String appid_lh = PropertiesUtils.getProperty("appid_lhn");
		String secret_lh = PropertiesUtils.getProperty("secret_lhn");*/
        if (StringUtils.isBlank(appid) || StringUtils.isBlank(secret)) {
            throw new AppException(ErrorCode.EXCEPTION_WECHAT_COUNT_NOT_EXIST, "微信公众号信息未配置，请联系系统管理员配置");
        }

        String token = weChatUserService.getAccessToken(appid, secret, redisKey);

        if (StringUtils.isBlank(token)) {
            throw new AppException(ErrorCode.EXCEPTION_WECHAT_SYSTEM_ERROR, "系统繁忙，请稍后重试");
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("appId", appid);
        param.put("secret", secret);
        param.put("redisKey", redisKey);
        Map<String, Object> wechatMap = weChatUserService.getUserInfoByToken(token, openId, param);
        Object groupId = wechatMap.get("groupId");

        param.clear();
        if (null == groupId || 0 == Integer.parseInt(groupId.toString())) {
            if (Constants.WECHAT_CHANNEL_EB.equals(wechatCode)) {
                groupId = Constants.DEFAULT_GROUP_EBSF;
            } else {
                groupId = 113;//默认groupId
            }
        }
        param.put("groupId", groupId);
        param.put("queueUsertype", Constants.QUEUE_USER_TYPE_BABY);
        param.put("optionStatus", Constants.DEPARTMENT_DEFAULT_QUEUE_STATUS);
        param.put("wechatCode", wechatCode);

        Map<String, Object> map = confCacheDao.selectDeptAndQueueIdByCode(param);
        if (null == map || org.springframework.util.StringUtils.isEmpty(map.get("deptId")) || org.springframework.util.StringUtils.isEmpty(map.get("queueId"))) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_QRCODE_INVALID, "无效二维码"));
        }
        deptCode = (String) map.get("code");
        String deptId = (String) map.get("deptId");
        String queueId = (String) map.get("queueId");
        String tenantId = (String) map.get("tenantId");

        //根据openId 查询手机号码
        param.clear();
        param.put("openId", openId);
        List<Map<String, Object>> list = confCacheDao.selectwechat(param);
        if (CollectionUtils.isEmpty(list) || org.springframework.util.StringUtils.isEmpty(list.get(0).get("phone_no"))) {
            rspMap.put("type", "00");
            rspMap.put("openId", openId);
            rspMap.put("deptCode", deptCode);
            return new ResultModel<Map<String, Object>>(rspMap);
//			throw (new AppException(ErrorCode.EXCEPTION_WECHATID_NOT_BIND_PHONENUM, "微信号还没有绑定手机号码"));
        }

        rspMap.put("wxNickName", wechatMap.get("wxNickName"));
        rspMap.put("wxHeadimgurl", wechatMap.get("wxHeadimgurl"));
        String phoneNum = (String) list.get(0).get("phone_no");

        //根据手机号 和租户 查询用户上个科室基本信息  //没有则跳转建档
        Map<String, Object> qryPtMap = new HashMap<String, Object>();
        qryPtMap.put("phoneNo", phoneNum);
//        qryPtMap.put("wechat_id", openId);
        qryPtMap.put("tenantId", tenantId);
        qryPtMap.put("userType", "1");
        List<Patient> ptList = patientdao.selectByPhoneNo(qryPtMap);
        Patient pt = null;
        if (CollectionUtils.isEmpty(ptList)) {
            rspMap.put("type", "03");
            rspMap.put("openId", openId);
            rspMap.put("deptCode", deptCode);
            return new ResultModel<Map<String, Object>>(rspMap);
//			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者记录不存在,请建档"));
        } else {
            pt = ptList.get(0);
            Long birthLong = ToolUtils.getCorrect(pt.getBirthday(), pt.getPregnancyDay());//生日时间戳
            String age = ToolUtils.getCommAgeByBirthday(DateUtil.getDate_8(new Date()), DateUtil.getDate_8(new Date(birthLong)));
            rspMap.put("age", age);
            rspMap.put("birthday", pt.getBirthday());
            rspMap.put("gender", pt.getGender());
            rspMap.put("pregnancyDay", pt.getPregnancyDay());
            rspMap.put("userName", pt.getUserName());
            rspMap.put("deptCode", deptCode);
            rspMap.put("userId", pt.getId());
//			rspMap.put("age",age);
        }

        //前端没有code传入的情况  根据usrId 租户id 查询队列和科室id
        Map<String, Object> ptMap = new HashMap<String, Object>();
        ptMap.put("userId", pt.getId());
        ptMap.put("tenantId", tenantId);
        ptMap.put("queueId", queueId);
        List<String> statulist = new ArrayList<String>();
        statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        ptMap.put("status", statulist);
        List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
        if (CollectionUtils.isEmpty(queueSchemeList)) { //还没有加入队列
            rspMap.put("type", "03");
            rspMap.put("openId", openId);
            rspMap.put("deptCode", deptCode);
            return new ResultModel<Map<String, Object>>(rspMap);
        }
        //取用户最近一次的 体重和身高
        List<Map<String, Object>> growthList = familyReportDAO.selectGrowthList(ptMap);
        if (!CollectionUtils.isEmpty(growthList)) {
            Float weight = (Float) growthList.get(0).get("weight");
            if (null != weight) {
                weight = weight * 1000;
            }
            Float height = (Float) growthList.get(0).get("height");
            rspMap.put("weight", weight);
            rspMap.put("height", height);
        }

        rspMap.put("type", "04");
        rspMap.put("deptId", deptId);
        rspMap.put("queueId", queueId);

        return new ResultModel<Map<String, Object>>(rspMap);
    }

    // 生长发育记录添加
    @ResponseBody
    @RequestMapping("/growth/addgrowth")
    public ResultModel<Map<String, Object>> addGrowthRecord(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in addgrowth----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in addGrowthRecord----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String userId = jsonData.getString("userId");
        String deptId = jsonData.getString("deptId");

        String weight = jsonData.getString("weight");
        String height = jsonData.getString("height");
        //String headCircumference = jsonData.getString("headCircumference");
        if (StringUtils.isEmpty(userId)) {
            logger.debug("out addGrowthRecord----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，用户ID不能为空");
        }

        if (StringUtils.isEmpty(deptId)) {
            logger.debug("out addGrowthRecord----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，科室ID不能为空");
        }
        if (StringUtils.isEmpty(weight)) {
            logger.debug("out addGrowthRecord----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，体重不能为空");
        }
        if (StringUtils.isEmpty(height)) {
            logger.debug("out getGrowthDetail----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，身高不能为空");
        }
        //20180410 去除头围必传校验
        /*if(StringUtils.isEmpty(headCircumference)){
        	logger.debug("out addGrowthRecord----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，头围不能为空");
        }*/

        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
        if (null == depObj) {
            throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
        }

        String tenantId = depObj.getTenantId();
        jsonData.put("tenantId", tenantId);
//        jsonData.put("authorName",authorName);
        String sourceType = jsonData.getString("sourceType");
        if (StringUtils.isEmpty(sourceType)) {
            jsonData.put("sourceType", Constants.SOURCE_TYPE_APP);
        } else {
            jsonData.put("sourceType", sourceType);
        }
        //20180410 如果没有传入remark字段
        if (StringUtils.isEmpty(jsonData.getString("remark"))) {
            jsonData.put("remark", "微信端/app新增生长发育数据");
        }

        Map<String, Object> retOut = familyReportService.addGrowthRecord(jsonData);

        try {
            if (!StringUtils.isEmpty(userId)) {
                Map<String, Object> userMap = new HashMap<String, Object>();
                userMap.put("userId", userId);
                userMap.put("tenantId", tenantId);
                Patient pt = patientdao.selectById(userMap);

                if (null != pt) {
                    Map<String, Object> paramRecord = new HashMap<String, Object>();
                    paramRecord.putAll(jsonData);
                    paramRecord.put("opUsertype", Constants.OPCODE_TYPE_PATIENT);
                    paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
                    paramRecord.put("authorId", userId);
                    paramRecord.put("userId", userId);
                    String remark = "患者【" + pt.getUserName() + "】录入生长发育监测数据";
                    paramRecord.put("remark", remark);
                    paramRecord.put("updateAccept", SeqUtil.getSeqNo());
                    paramRecord.put("opCode", Constants.OP_CODE_1011);
                    patientInfoHisService.saveOperationRecord(paramRecord);

                    //诊间扫码集成做的评估  将记录id同步回去
                    Object answerId = retOut.get("id");
                    if (Constants.PATIENT_SOURCE_TYPE_SCAN.equals(sourceType)
                            && !org.springframework.util.StringUtils.isEmpty(answerId)) {
                        //
                        Map<String, Object> synchMap = new HashMap<String, Object>();
//						synchMap.put("sourceType",Constants.PATIENT_SOURSE_TYPE_SCAN);
                        paramRecord.put("busiId", answerId);
                        synchMap.put(Constants.MQ_MESSAGE_BODY, paramRecord);
                        //业务类型
                        synchMap.put(Constants.MQ_MESSAGE_TYPE, Constants.CONSUMER_TYPE_EVALUATION_TO_SCAN); //问卷发到医生端  不需要区分新增和更新
                        HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl2"),JSON.toJSONString(synchMap));
                    }
                }
            }

        } catch (Exception e) {
            logger.error("保存上传生长发育操作记录表报错", e);
        }

        return new ResultModel<Map<String, Object>>(retOut);
    }

    // 生长发育详情查询
    @ResponseBody
    @RequestMapping("/growth/detail")
    public ResultModel<Map<String, Object>> getGrowthDetail(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthDetail----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthDetail----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String growthRecordId = jsonData.getString("growthRecordId");
        if (StringUtils.isEmpty(growthRecordId)) {
            logger.debug("out getGrowthDetail----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，生长发育评估记录ID不能为空");
        }

        String deptId = jsonData.getString("deptId");
        if (StringUtils.isEmpty(deptId)) {
            logger.debug("out addGrowthRecord----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，科室ID不能为空");
        }

        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
        if (null == depObj) {
            throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
        }

        String tenantId = depObj.getTenantId();

        //增加 	年龄计算类型	曲线类型	标志
        String ageType = jsonData.getString("ageType");
        String scoreType = jsonData.getString("scoreType");
        //如果为空则传入默认值
        if (StringUtils.isEmpty(ageType)) {
            ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        } else {
            if (!Constants.GROWTH_AGE_TYPE_CORRECT.equals(ageType) && !Constants.GROWTH_AGE_TYPE_ACTUAL.equals(ageType)) {
                ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
            }
        }
        if (StringUtils.isEmpty(scoreType)) {
            scoreType = Constants.GROWTH_SCORE_PERCENT;
        } else {
            if (!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)) {
                scoreType = Constants.GROWTH_SCORE_PERCENT;
            }
        }

        paramMap.put("ageType", ageType);
        paramMap.put("scoreType", scoreType);
        paramMap.put("tenantId", tenantId);
        paramMap.put("deptId", deptId);
//        paramMap.put("doctorName",doctorName);

        paramMap.put("growthRecordId", growthRecordId);
        Map<String, Object> retOut = familyReportService.getGrowthDeatail(paramMap);
        retOut.remove("actualResult");

        return new ResultModel<Map<String, Object>>(retOut);
    }

    // 生长发育详情查询
    @ResponseBody
    @RequestMapping("/growth/curvedata")
    public ResultModel<Map<String, Object>> getGrowthCurvedata(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in getGrowthCurvedata----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 后续重写异常类
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参节点错误，非json格式！"));
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            logger.warn("in getGrowthCurvedata----no data node...");
            // 前台必须传data节点，否则报错返回（后续重写异常类）
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String channel = jsonData.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String growthRecordId = jsonData.getString("growthRecordId");
        if (StringUtils.isEmpty(growthRecordId)) {
            logger.debug("out getGrowthCurvedata----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，生长发育评估记录ID不能为空");
        }

        String deptId = jsonData.getString("deptId");
        if (StringUtils.isEmpty(deptId)) {
            logger.debug("out getGrowthCurvedata----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，科室ID不能为空");
        }

        String userId = jsonData.getString("userId");
        if (StringUtils.isEmpty(userId)) {
            logger.debug("out getGrowthCurvedata----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，用户ID不能为空");
        }

        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
        if (null == depObj) {
            throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
        }

        String tenantId = depObj.getTenantId();

        //增加 	年龄计算类型	曲线类型	标志
        String ageType = jsonData.getString("ageType");
        String scoreType = jsonData.getString("scoreType");
        //如果为空则传入默认值
        if (StringUtils.isEmpty(ageType)) {
            ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
        } else {
            if (!Constants.GROWTH_AGE_TYPE_CORRECT.equals(ageType) && !Constants.GROWTH_AGE_TYPE_ACTUAL.equals(ageType)) {
                ageType = Constants.GROWTH_AGE_TYPE_CORRECT;
            }
        }
        if (StringUtils.isEmpty(scoreType)) {
            scoreType = Constants.GROWTH_SCORE_PERCENT;
        } else {
            if (!Constants.GROWTH_SCORE_PERCENT.equals(scoreType) && !Constants.GROWTH_SCORE_ZSCORE.equals(scoreType)) {
                scoreType = Constants.GROWTH_SCORE_PERCENT;
            }
        }

        paramMap.put("ageType", ageType);
        paramMap.put("scoreType", scoreType);
        paramMap.put("tenantId", tenantId);
        paramMap.put("deptId", deptId);
        paramMap.putAll(jsonData);
//        paramMap.put("doctorName",doctorName);

        paramMap.put("growthRecordId", growthRecordId);
        Map<String, Object> retOut = familyReportService.getGrowthCurvedata(paramMap);

        return new ResultModel<Map<String, Object>>(retOut);
    }

    /**
     * 查询患者的所有生长发育评估报告（包括医生的指导建议）。
     * @param arg
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/evaluation/scorehislist")
    @ResponseBody
    public QueryModel<Map<String, Object>> getHistoryScore(@RequestBody String arg,
                                                           HttpServletRequest request) throws Exception {
        logger.info("in getHistoryScore----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

		 /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String userId = requestParam.getString("userId");
        if (StringUtils.isEmpty(userId)) {
            logger.info("out getHistoryScore----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者ID不能为空");
        }

        String deptId = requestParam.getString("deptId");
        if (StringUtils.isEmpty(deptId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "随访科室ID不能为空!");
        }

        String type = requestParam.getString("evaluationType");
        /*if(StringUtils.isEmpty(type)){
        	logger.info("out getHistoryScore----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，随访评测类型不能为空");
        }
*/
        List<String> typeList = new ArrayList<String>();
        if (StringUtils.isEmpty(type)) {
            typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD);
            typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_ASQ);
//            typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_SDQ);
        } else {
            typeList.add(type);
        }


        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
        if (null == depObj) {
            throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
        }
        final String tenantId = depObj.getTenantId();// 租户id

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);
        paramMap.put("userId", userId);
        paramMap.put("typeList", typeList);
        paramMap.put("tenantId", tenantId);
        paramMap.put("sourseType", Constants.SOURCE_TYPE_APP);
        List<Map<String, Object>> list = followEvaluationService.selectPtEvaluationResults(paramMap);
        logger.info("++++getHistoryScore() call followEvaluationService.selectPtEvaluationResults() result size:"+list.size());

        //生长发育记录
        List<Map<String, Object>> growthList = familyReportService.getGrowthHistory(paramMap);
        list.addAll(growthList);
        final int total = growthList.size();
        if (!CollectionUtils.isEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                String birthday = (null == list.get(i).get("birthday")) ? "" : list.get(i).get("birthday").toString();
                int pregnancyWeek = null == list.get(i).get("pregnancyWeek") ? 40 : Integer.parseInt(list.get(i).get("pregnancyWeek").toString());
                String testTime = (null == list.get(i).get("testTime")) ? "" : list.get(i).get("testTime").toString();
                String title = "";
                if (!StringUtils.isEmpty(birthday) && !StringUtils.isEmpty(testTime)) {
                    Long birthLong = ToolUtils.getCorrect(birthday, pregnancyWeek);//生日时间戳
                    long ageMonth = (long) ((DateUtil.getDate(testTime).getTime() - birthLong) / (1000 * 60 * 60 * 24) / 30.4);
                    if (Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(list.get(i).get("type"))) {
                        title = ageMonth + "月龄养育环境测量问卷";
                    } else if (Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(list.get(i).get("type"))) {
                        title = ageMonth + "月龄智能发育评估问卷";
                    } else if (Constants.FOLLOW_EVALUATION_PREGNANT_GROWTH.equals(list.get(i).get("type"))) {
                        title = ageMonth + "月龄生长发育";
                        list.get(i).put("answerId", list.get(i).get("growthRecordId"));
                    }
                } else {
                    if (Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(list.get(i).get("type"))) {
                        title = "养育环境测量问卷";
                    } else if (Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(list.get(i).get("type"))) {
                        title = "智能发育评估问卷";
                    } else if (Constants.FOLLOW_EVALUATION_PREGNANT_GROWTH.equals(list.get(i).get("type"))) {
                        title = "月龄生长发育";
                        list.get(i).put("answerId", list.get(i).get("growthRecordId"));
                    }
                }
                list.get(i).put("title", title);
                //list.get(i).remove("result");
                list.get(i).remove("answerResult");
                //list.get(i).remove("userName");
                list.get(i).remove("babyName");
                //list.get(i).remove("actualResult");
                list.get(i).remove("testAge");
            }
        	//total= followEvaluationService.selectPtEvaluationResultCount(paramMap);
        }

        logger.info("out getHistoryScore----arg==" + list);
        return new QueryModel<Map<String, Object>>(list, total);
    }


    @RequestMapping("/getOpenId")
    @ResponseBody
    public ResultModel<Object> getOpenId(@RequestBody String arg,
                                         HttpServletRequest request) throws Exception {
        logger.info("in getOpenId----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String code = requestParam.getString("code");
        if (StringUtils.isEmpty(code)) {
            logger.info("out getHistoryScore----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，code不能为空");
        }

        String wechatCode = requestParam.getString("wechatCode");
        if (StringUtils.isBlank(wechatCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode不能为空！"));
        }

        String appid = "";
        String secret = "";
        if (Constants.WECHAT_CHANNEL_LH.equals(wechatCode)) {
            appid = PropertiesUtils.getProperty("appid_lhn");
            secret = PropertiesUtils.getProperty("secret_lhn");
        } else if (Constants.WECHAT_CHANNEL_EB.equals(wechatCode)) {
            appid = PropertiesUtils.getProperty("appid_ebsf");
            secret = PropertiesUtils.getProperty("secret_ebsf");
        } else {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "wechatCode值不正确！"));
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("appId", appid);
        param.put("secret", secret);
        param.put("code", code);
        Map<String, Object> map = weChatUserService.getOpenId(param);
        /*Map<String,Object> map = new HashMap<String,Object>();
        map.put("openId",openid);*/
        return new ResultModel<Object>(map);
    }

    @RequestMapping("/getEbsfOpenId")
    @ResponseBody
    public ResultModel<Object> getEbsfOpenId(@RequestBody String arg,
                                             HttpServletRequest request) throws Exception {
        logger.info("in getOpenId----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String code = requestParam.getString("code");
        if (StringUtils.isEmpty(code)) {
            logger.info("out getHistoryScore----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，code不能为空");
        }

        String appid_ebsf = PropertiesUtils.getProperty("appid_ebsf");
        String secret_ebsf = PropertiesUtils.getProperty("secret_ebsf");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("appId", appid_ebsf);
        param.put("secret", secret_ebsf);
        param.put("code", code);
        Map<String, Object> map = weChatUserService.getOpenId(param);
        /*Map<String,Object> map = new HashMap<String,Object>();
        map.put("openId",openid);*/
        return new ResultModel<Object>(map);
    }

    @RequestMapping("/growth/getGuide")
    @ResponseBody
    public ResultModel<Map<String, Object>> getGrowthGuide(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("in getGrowthGuide----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String growthRecordId = requestParam.getString("growthRecordId");
        if (StringUtils.isEmpty(growthRecordId)) {
            logger.info("out getGuide----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，记录ID不能为空");
        }

        Map<String, Object> paramsMap = new HashMap<String, Object>();
        //aims评估结果意见 从表查询
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("growthRecordId", requestParam.get("growthRecordId"));
        param.putAll(requestParam);

        Map<String, Object> resultMap = familyReportDAO.selectGrowthDetails(param);

        if (null != resultMap) {
            Map<String, Object> ptMap = new HashMap<String, Object>();
            ptMap.put("userId", resultMap.get("userId"));
            ptMap.put("tenantId", resultMap.get("tenantId"));
            Patient pt = patientService.getPatient(ptMap);
            if (pt == null) {
                throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
            }

            Long birthLong = ToolUtils.getCorrect(pt.getBirthday(), pt.getPregnancyDay());//生日时间戳
            long ageDay = (DateUtil.getDate_8(resultMap.get("testTime").toString()).getTime() - birthLong) / (1000 * 60 * 60 * 24);
            long ageMonth = (long) (ageDay / 30.4);
            String title = "";
            String subTitle = "";
            title = ageMonth + "月生长发育";
            subTitle = ageMonth + "月龄(训练指导)";
            paramsMap.put("title", title);
            paramsMap.put("subTitle", subTitle);
            paramsMap.put("ageMonth", ageMonth);
            paramsMap.put("testTime", resultMap.get("testTime"));

            param.put("evaluationId", requestParam.get("growthRecordId"));
            List<Map<String, Object>> list = followEvaluationService.getEvaluationGuides(param);
            paramsMap.put("guideList", list);
        } else {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TEMPERATURE_NOT_EXIST,
                    "评估记录不存在");
        }
//		paramsMap.put("success", true);
        return new ResultModel<Map<String, Object>>(paramsMap);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/queryFuAssessContTmpl")
    @ResponseBody
    public ResultModel<Object> queryFuAssessContTmpl(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("in queryFuAssessContTmpl----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

           /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String templateId = requestParam.getString("busiId");
        if (StringUtils.isEmpty(templateId)) {
            logger.info("out queryFuAssessContTmpl----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷模板不能为空");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("busiId", templateId);
        Map<String, Object> outMap = patientFollowService.getPatientFollowContTempl(paramMap);
        if (null != outMap.get("quesInfo") && outMap.get("quesInfo") instanceof List) {
            List<Object> list = (List<Object>) outMap.get("quesInfo");
            if (!CollectionUtils.isEmpty(list)) {
                outMap.put("quesInfo", list.get(0)); //问卷只返回一种  去掉多的一层
            }
        }
        return new ResultModel<Object>(outMap);
    }

    @RequestMapping("/submitPtFuAssessCont")
    @ResponseBody
    public ResultModel<Object> submitPtFuAssessCont(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("in submitPtFuAssessCont----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

          /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String busiId = requestParam.getString("busiId");
        if (StringUtils.isEmpty(busiId)) {
            logger.info("out submitPtFuAssessCont----arg== null");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，问卷模板不能为空");
        }
        Map<String, Object> oprInfoMap = requestParam;

        // 入参校验
        String opCode = Constants.OP_CODE_1114;
        String opType = Constants.OP_TYPE_SELF;
        String opNote = "用户填写孕期保健和母乳问卷";

        String userId = requestParam.getString("userId");
        if (StringUtils.isBlank(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id为空！"));
        }
        String tmplVerInfo = requestParam.getString("tmplVerInfo");
        if (StringUtils.isBlank(tmplVerInfo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，模板id为空！"));
        }

        String deptId = requestParam.getString("deptId");
        if (StringUtils.isBlank(tmplVerInfo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，模板id为空！"));
        }

        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
        if (null == depObj) {
            throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
        }
        String tenantId = depObj.getTenantId();// 租户id
        // 来源渠道，入参若无，则默认微信公众号渠道
        String sourceType = (String) requestParam.get("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            sourceType = Constants.PATIENT_SOURCE_TYPE_WECHAT_OFFICIAL_ACCOUNT;
        }

        oprInfoMap.put("opCode", opCode);
        oprInfoMap.put("opType", opType);
        oprInfoMap.put("opNote", opNote);

        oprInfoMap.put("authorName", "");
        oprInfoMap.put("updateTime", DateUtil.getTimeString(DateUtil.getSysDateA()));// 操作时间
        oprInfoMap.put("authorId", userId);
        oprInfoMap.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));// 操作流水
        oprInfoMap.put("tenantId", tenantId);
        oprInfoMap.put("sourceType", sourceType);

        Map<String, Object> busiInfoMap = new HashMap<String, Object>();
        busiInfoMap.put("busiId", busiId);
        busiInfoMap.put("patientId", userId);
        busiInfoMap.put("tmplVerInfo", tmplVerInfo);

        requestParam.put(Constants.INF_INPUTPARAM_OPRINFO_FIELD, oprInfoMap);
        requestParam.put("busiInfo", busiInfoMap);
        Map<String, Object> retout = patientFollowService.savePtAssessContent(requestParam);
        return new ResultModel<Object>(retout);
    }

    //先按现有逻辑 查询做过的问卷
    @RequestMapping("/getComList")
    @ResponseBody
    public ResultModel<Object> getComList(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("in getComList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

          /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
        String channel = requestParam.getString("channel");
        if (null == channel || !PropertiesUtils.getProperty("channel").equals(channel)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
        }

        String userId = requestParam.getString("userId");
        if (StringUtils.isBlank(userId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id为空！"));
        }
        String deptId = requestParam.getString("deptId");
        if (StringUtils.isBlank(deptId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，科室ID不能为空！"));
        }
        DepartmentBasic depObj = deparmentBasicService.getDepartmentBasicDetails(deptId);
        if (null == depObj) {
            throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST, "科室信息不存在");
        }
        String tenantId = depObj.getTenantId();// 租户id
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);
        paramMap.put("tenantId", tenantId);
        List<Map<String, Object>> retout = weChatUserService.getComList(paramMap);

        return new ResultModel<Object>(retout);
    }

    @RequestMapping("/wechatInit")
    @ResponseBody
    public void wechatInitForLH(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("in wechatInitForLH----arg==wechatInitForLH");
        String hostName = PropertiesUtils.getProperty("monthBaseUrl");
        Map<String, Object> data = ToolUtils.getParam(request);
        logger.info("data:[" + JSON.toJSONString(data) + "]");
        String timestamp = (String) data.get("timestamp");
        String nonce = (String) data.get("nonce");
        String wxtoken = Constants.TOKEN;
        String signature = (String) data.get("signature");
        String responseStr = "";
        try {
            if (signature.equalsIgnoreCase(ToolUtils.getSignature(timestamp, nonce, wxtoken))) {
                if (org.springframework.util.StringUtils.isEmpty(data.get("echostr"))) {
                    String postStr = ToolUtils.readStreamParameter(request.getInputStream());
                    logger.info("requestStr:::" + postStr);
                    Map<String, Object> wxData = ToolUtils.getXmlElementData(postStr);
                    // 获取微信POST过来的数据
                    // 用户ID，OPEN_ID
                    String fromUserName = (String) wxData.get("FromUserName");
                    // 微信原始ID
					String toUserName = (String)wxData.get("ToUserName");
                    // 消息类型
                    String msgType = (String) wxData.get("MsgType");
                    // 事件类型
                    String event = (String) wxData.get("Event");

                    String appid_lh = PropertiesUtils.getProperty("appid_lhn");
                    String secret_lh = PropertiesUtils.getProperty("secret_lhn");
                    if (StringUtils.isBlank(appid_lh) || StringUtils.isBlank(secret_lh)) {
                        logger.error("微信公众号信息未配置，请联系系统管理员配置");
                        return;
                    }

                    String json = "";
                    String action = "";
                    String title = "";
                    String hospitalImage = "";
                    String accessToken = weChatUserService.getAccessToken(appid_lh, secret_lh, Constants.ACCESS_TOKEN_LEHUI);
                    String groupId = "";
                    if ("event".equals(msgType)) {// 事件消息
                        if ("subscribe".equals(event)) {
                            logger.info("in wechatInitForLH----关注公众号");
                            String key = (String) wxData.get("EventKey");
                            if (!StringUtils.isEmpty(key)) {
                                String qrCode = key.split("_")[1];
                                action = Constants.GROUP_MEMBER_UPDATE + accessToken;
//				                  action="https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token="+accessToken;
                                String content = "";
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("qrCode", qrCode);
                                map.put("wechatCode", Constants.WECHAT_CHANNEL_LH);
                                BsWxContent wxContent = confCacheDao.selectWxContent(map);
                                if (null == wxContent) {
                                    logger.error("[" + qrCode + "]对应二维码信息未配置，请联系系统管理员配置");
                                    return;
                                }
                                groupId = wxContent.getGroupid();

                                json = "{\"openid\":\"" + fromUserName + "\",\"to_groupid\":" + groupId + "}";
                                content = wxContent.getHuanyingtext();
                                title = wxContent.getTitle();
                                hospitalImage = wxContent.getHospitalimage();
                                ToolUtils.getWechatInf(action, json);
                                //欢迎语
//				                  action="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
                                action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                                json = "{\"touser\": \"" + fromUserName + "\",\"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
                                // connectWeiXinInterface(action,json);
                                String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url1 = hostName + "index.html?viewType=1&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url2 = hostName + "index.html?viewType=2&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url3 = hostName + "index.html?viewType=3&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url4 = hostName + "index.html?viewType=4&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
//				                  String url6="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid_lh +"&redirect_uri="+hostName+"html/user/main.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

                                String welcomeSpeech = title + "，亲爱的家长您好，评测请点下方“专业评测”";
                                json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+ welcomeSpeech +"\"}}";
//                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
//                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
////										"{\"title\":\"新用户请建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
////										"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
////					              			"{\"title\":\"评测记录\",\"description\":\"\",\"url\":\""+url6+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E9%80%89%E4%B8%AD%E4%B8%AA%E4%BA%BA%E4%B8%AD%E5%BF%83.png\"}"+
//                                        "]}}";
                                if (qrCode.equals("14")) {
                                    String url5 = hostName + "index.html?viewType=6&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                    json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+ welcomeSpeech +"\"}}";
//                                    json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
//                                            "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
////											"{\"title\":\"孕期保健和母乳喂养调查\",\"description\":\"\",\"url\":\""+url5+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%AF%8D%E4%B9%B3%E5%96%82%E5%85%BB.png\"},"+
////											"{\"title\":\"宝宝建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
////											"{\"title\":\"宝宝生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////											"{\"title\":\"宝宝智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////											"{\"title\":\"宝宝养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
////				                  			"{\"title\":\"评测记录\",\"description\":\"\",\"url\":\""+url6+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E9%80%89%E4%B8%AD%E4%B8%AA%E4%BA%BA%E4%B8%AD%E5%BF%83.png\"}"+
//                                            "]}}";
                                }
                                ToolUtils.getWechatInf(action, json);

                                Map<String, Object> wechatmap = confCacheDao.selectgroupIdByopenId(fromUserName);

                                if (wechatmap == null){
                                    BsWechatAllfans bsWechatAllfans = new BsWechatAllfans();
                                    bsWechatAllfans.setId(SeqUtil.getSeqNo());
                                    bsWechatAllfans.setNewOpenid(fromUserName);
                                    bsWechatAllfans.setWechatId(toUserName);
                                    bsWechatAllfans.setCreateTime(DateUtil.getSysDateA());
                                    bsWechatAllfans.setRemark(fromUserName);
                                    bsWechatAllfans.setBak1("lovely");
                                    bsWechatAllfans.setBak2(null);
                                    bsWechatAllfans.setBak3(null);
                                    bsWechatAllfans.setGroupId(groupId);
                                    confCacheDao.saveWechatAllFans(bsWechatAllfans);
                                } else {
                                    Map<String, Object> fansmap = new HashMap<String, Object>();
                                    fansmap.put("groupId",groupId);
                                    fansmap.put("openId",fromUserName);
                                    confCacheDao.updategroupIdByopenId(fansmap);
                                }
                            } else {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("qrCode", "23");
                                map.put("wechatCode", Constants.WECHAT_CHANNEL_LH);
                                BsWxContent wxContent = confCacheDao.selectWxContent(map);
                                if (null == wxContent) {
                                    logger.error("[" + 23 + "]对应二维码信息未配置，请联系系统管理员配置");
                                    return;
                                }
                                groupId = wxContent.getGroupid();
                                title = wxContent.getTitle();
                                hospitalImage = wxContent.getHospitalimage();
                                action = Constants.GROUP_MEMBER_UPDATE + accessToken;
//			                    action="https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token="+accessToken;
                                json = "{\"openid\":\"" + fromUserName + "\",\"to_groupid\":" + groupId + "}";
//			                    json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+wxContent.getHuanyingtext()+"\"}}";
                                ToolUtils.getWechatInf(action, json);
                                //欢迎语
//				                action="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
                                action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                                String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url1 = hostName + "index.html?viewType=1&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url2 = hostName + "index.html?viewType=2&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url3 = hostName + "index.html?viewType=3&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url4 = hostName + "index.html?viewType=4&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
//				            	String url6="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid_lh +"&redirect_uri="+hostName+"html/user/main.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                                //String url5=hostName+"index.html?viewType=6&openId="+toUserOpenId+"&code="+wxContent.getCode();
                                String welcomeSpeech = title + "，亲爱的家长您好，评测请点下方“专业评测”";
                                json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+ welcomeSpeech +"\"}}";
//                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
//                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
////										"{\"title\":\"新用户请建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
////										"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
//                                        "]}}";
                                ToolUtils.getWechatInf(action, json);

                                Map<String, Object> wechatmap = confCacheDao.selectgroupIdByopenId(fromUserName);

                                if (wechatmap == null){
                                    BsWechatAllfans bsWechatAllfans = new BsWechatAllfans();
                                    bsWechatAllfans.setId(SeqUtil.getSeqNo());
                                    bsWechatAllfans.setNewOpenid(fromUserName);
                                    bsWechatAllfans.setWechatId(toUserName);
                                    bsWechatAllfans.setCreateTime(DateUtil.getSysDateA());
                                    bsWechatAllfans.setRemark(fromUserName);
                                    bsWechatAllfans.setBak1("lovely");
                                    bsWechatAllfans.setBak2(null);
                                    bsWechatAllfans.setBak3(null);
                                    bsWechatAllfans.setGroupId(groupId);
                                    confCacheDao.saveWechatAllFans(bsWechatAllfans);
                                } else {
                                    Map<String, Object> fansmap = new HashMap<String, Object>();
                                    fansmap.put("groupId",groupId);
                                    fansmap.put("openId",fromUserName);
                                    confCacheDao.updategroupIdByopenId(fansmap);
                                }
                            }
                        } else if ("SCAN".equals(event)) {
                            String key = (String) wxData.get("EventKey");
                            logger.info("in wechatInitForLH----扫码操作,[" + key + "]");
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("qrCode", key);
                            map.put("wechatCode", Constants.WECHAT_CHANNEL_LH);
                            BsWxContent wxContent = confCacheDao.selectWxContent(map);
                            if (null == wxContent) {
                                logger.error("[" + 23 + "]对应二维码信息未配置，请联系系统管理员配置");
                                return;
                            }
                            groupId = wxContent.getGroupid();
//		                    action="https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token="+accessToken;
                            action = Constants.GROUP_MEMBER_UPDATE + accessToken;
                            json = "{\"openid\":\"" + fromUserName + "\",\"to_groupid\":" + groupId + "}";
                            title = wxContent.getTitle();
                            hospitalImage = wxContent.getHospitalimage();
                            ToolUtils.getWechatInf(action, json);

                            Map<String, Object> wechatmap = confCacheDao.selectgroupIdByopenId(fromUserName);

                            if (wechatmap != null){
                                Map<String, Object> fansmap = new HashMap<String, Object>();
                                fansmap.put("groupId",groupId);
                                fansmap.put("openId",fromUserName);
                                confCacheDao.updategroupIdByopenId(fansmap);
                            }
//		                    action="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
                            action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                            String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                            String url1 = hostName + "index.html?viewType=1&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                            String url2 = hostName + "index.html?viewType=2&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                            String url3 = hostName + "index.html?viewType=3&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                            String url4 = hostName + "index.html?viewType=4&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
//		                 	String url6="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid_lh +"&redirect_uri="+hostName+"html/user/main.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                            String welcomeSpeech = title + "，亲爱的家长您好，评测请点下方“专业评测”";
                            if (groupId.equals("113")) {
                                String url5 = hostName + "index.html?viewType=6&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+ welcomeSpeech +"\"}}";
//                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
//                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
////										"{\"title\":\"孕期保健和母乳喂养调查 \",\"description\":\"\",\"url\":\""+url5+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%AF%8D%E4%B9%B3%E5%96%82%E5%85%BB.png\"},"+
////										"{\"title\":\"宝宝建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
////										"{\"title\":\"宝宝生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"宝宝智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"宝宝养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
//                                        "]}}";
                            } else {
                                json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+ welcomeSpeech +"\"}}";
//                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
//                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
////										"{\"title\":\"新用户请建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
////										"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
////										"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
//                                        "]}}";
                            }
                            ToolUtils.getWechatInf(action, json);
                        } else if ("CLICK".equals(event)) {
                            String key = (String) wxData.get("EventKey");
                            if (("mfpc").equals(key)) {
                                String code = "";
//				            	String sdUrl="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+fromUserName+"&lang=zh_CN";
                                String sdUrl = Constants.GET_USER_URL + accessToken + "&openid=" + fromUserName + "&lang=zh_CN";
                                String userStr = ToolUtils.getWechatInf(sdUrl, null);
                                JSONObject result = null;
                                if (userStr != null) {
                                    result = JSONObject.parseObject(userStr);
                                    Integer group = (Integer) result.get("groupid");
                                    if (group != null && group != 0) {
                                        code = group + "";
                                    } else {
                                        code = "122";
                                    }
                                }
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("groupId", code);
                                map.put("wechatCode", Constants.WECHAT_CHANNEL_LH);
                                BsWxContent wxContent = confCacheDao.selectWxContent(map);
                                if (null == wxContent) {
                                    logger.error("[" + 23 + "]对应二维码信息未配置，请联系系统管理员配置");
                                    return;
                                }
                                title = wxContent.getTitle();
                                hospitalImage = wxContent.getHospitalimage();
                                String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url1 = hostName + "index.html?viewType=1&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url2 = hostName + "index.html?viewType=2&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url3 = hostName + "index.html?viewType=3&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                String url4 = hostName + "index.html?viewType=4&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
//				             	String url6="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid_lh+"&redirect_uri="+hostName+"html/user/main.html&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//				             	action="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
                                action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
//										"{\"title\":\"新用户请建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
//										"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
//										"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
//										"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
                                        "]}}";
                                if ("14".equals(wxContent.getCode())) {
                                    String url5 = hostName + "index.html?viewType=6&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_LH;
                                    ;
                                    json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
                                            "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
//											"{\"title\":\"孕期保健和母乳喂养调查 \",\"description\":\"\",\"url\":\""+url5+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%AF%8D%E4%B9%B3%E5%96%82%E5%85%BB.png\"},"+
//											"{\"title\":\"宝宝建档 \",\"description\":\"\",\"url\":\""+url1+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%BB%BA%E6%A1%A3%E4%BF%A1%E6%81%AF1.png\"}," +
//											"{\"title\":\"宝宝生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
//											"{\"title\":\"宝宝智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
//											"{\"title\":\"宝宝养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
                                            "]}}";
                                }
                                ToolUtils.getWechatInf(action, json);
                            }
                        }
                    }
                } else {
                    logger.info("echostr:::" + data.get("echostr"));
                    responseStr = (String) data.get("echostr");
                    response.getWriter().write(responseStr);
                }
            } else {
                logger.info("token check failed");
                responseStr = "Access Forbidden";
                response.getWriter().write(responseStr);
            }
        } catch (Exception e) {
            logger.error("wechatInitForLH Error {}", e);
        }
    }

    @RequestMapping("/wechatInitForEbsf")
    @ResponseBody
    public void wechatInitForEbsf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("in wechatInitForEbsf----arg==wechatInitForEbsf");
        String hostName = PropertiesUtils.getProperty("monthBaseUrl");
        Map<String, Object> data = ToolUtils.getParam(request);
        logger.info("data:[" + JSON.toJSONString(data) + "]");
        String timestamp = (String) data.get("timestamp");
        String nonce = (String) data.get("nonce");
        String wxtoken = Constants.TOKEN;
        String signature = (String) data.get("signature");
        String responseStr = "";
        try {
            if (signature.equalsIgnoreCase(ToolUtils.getSignature(timestamp, nonce, wxtoken))) {
                if (org.springframework.util.StringUtils.isEmpty(data.get("echostr"))) {
                    String postStr = ToolUtils.readStreamParameter(request.getInputStream());
                    logger.info("requestStr:::" + postStr);
                    Map<String, Object> wxData = ToolUtils.getXmlElementData(postStr);
                    // 获取微信POST过来的数据
                    // 用户ID，OPEN_ID
                    String fromUserName = (String) wxData.get("FromUserName");
                    // 微信原始ID
//					String toUserName = (String)wxData.get("ToUserName");
                    // 消息类型
                    String msgType = (String) wxData.get("MsgType");
                    // 事件类型
                    String event = (String) wxData.get("Event");

                    String appid_ebsf = PropertiesUtils.getProperty("appid_ebsf");
                    String secret_ebsf = PropertiesUtils.getProperty("secret_ebsf");

                    String appUrl = PropertiesUtils.getProperty("appUrl");
                    if (StringUtils.isBlank(appid_ebsf) || StringUtils.isBlank(secret_ebsf)) {
                        logger.error("微信公众号信息未配置，请联系系统管理员配置");
                        return;
                    }

                    String json = "";
                    String action = "";
                    String title = "";
                    String hospitalImage = "";
                    String accessToken = weChatUserService.getAccessToken(appid_ebsf, secret_ebsf, Constants.ACCESS_TOKEN_EBSF);
                    String groupId = "";
                    if ("event".equals(msgType)) {// 事件消息
                        if ("subscribe".equals(event)) {
                            logger.info("in wechatInitForEbsf----关注公众号");
                            String key = (String) wxData.get("EventKey");
                            if (!StringUtils.isEmpty(key)) {
                                String qrCode = key.split("_")[1];
                                action = Constants.GROUP_MEMBER_UPDATE + accessToken;
                                String content = "";
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("qrCode", qrCode);
                                map.put("wechatCode", Constants.WECHAT_CHANNEL_EB);
                                BsWxContent wxContent = confCacheDao.selectWxContent(map);
                                if (null == wxContent) {
                                    logger.error("[" + qrCode + "]对应二维码信息未配置，请联系系统管理员配置");
                                    return;
                                }
                                groupId = wxContent.getGroupid();
                                json = "{\"openid\":\"" + fromUserName + "\",\"to_groupid\":" + groupId + "}";
                                content = wxContent.getHuanyingtext();
                                title = wxContent.getTitle();
                                hospitalImage = wxContent.getHospitalimage();
                                ToolUtils.getWechatInf(action, json);  //更新分组
                                //欢迎语
                                action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                                json = "{\"touser\": \"" + fromUserName + "\",\"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
                                // connectWeiXinInterface(action,json);
                                String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_EB;
				                  /*String url1=hostName+"index.html?viewType=1&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                  String url2=hostName+"index.html?viewType=2&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                  String url3=hostName+"index.html?viewType=3&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                  String url4=hostName+"index.html?viewType=4&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;*/

                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
                                        "{\"title\":\"用户端APP下载 \",\"description\":\"\",\"url\":\"" + appUrl + "\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/app.png\"}," +
					              			/*"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
					              			"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
					              			"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+*/
                                        "]}}";
                                ToolUtils.getWechatInf(action, json);
                            } else {
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("qrCode", Constants.DEFAULT_QRCODE_EBSF);//默认进 公司分组
                                map.put("wechatCode", Constants.WECHAT_CHANNEL_EB);
                                BsWxContent wxContent = confCacheDao.selectWxContent(map);
                                if (null == wxContent) {
                                    logger.error("[" + 1 + "]对应二维码信息未配置，请联系系统管理员配置");
                                    return;
                                }
                                groupId = wxContent.getGroupid();
                                title = wxContent.getTitle();
                                hospitalImage = wxContent.getHospitalimage();
                                action = Constants.GROUP_MEMBER_UPDATE + accessToken;
                                json = "{\"openid\":\"" + fromUserName + "\",\"to_groupid\":" + groupId + "}";
//			                    json = "{\"touser\": \""+fromUserName+"\",\"msgtype\": \"text\", \"text\": {\"content\": \""+wxContent.getHuanyingtext()+"\"}}";
                                ToolUtils.getWechatInf(action, json); //更新分组
                                //欢迎语
                                action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                                String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_EB;
				                /*String url1=hostName+"index.html?viewType=1&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                String url2=hostName+"index.html?viewType=2&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				                String url3=hostName+"index.html?viewType=3&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
				            	String url4=hostName+"index.html?viewType=4&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;*/
                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
                                        "{\"title\":\"用户端APP下载\",\"description\":\"\",\"url\":\"" + appUrl + "\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/app.png\"}," +
				              			/*"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
				              			"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
				              			"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+*/
                                        "]}}";
                                ToolUtils.getWechatInf(action, json);
                            }
                        } else if ("SCAN".equals(event)) {
                            String key = (String) wxData.get("EventKey");
                            logger.info("in wechatInitForEbsf----扫码操作,[" + key + "]");
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("qrCode", key);
                            map.put("wechatCode", Constants.WECHAT_CHANNEL_EB);
                            BsWxContent wxContent = confCacheDao.selectWxContent(map);
                            if (null == wxContent) {
                                logger.error("[" + key + "]对应二维码信息未配置，请联系系统管理员配置");
                                return;
                            }
                            groupId = wxContent.getGroupid();
                            action = Constants.GROUP_MEMBER_UPDATE + accessToken;
                            json = "{\"openid\":\"" + fromUserName + "\",\"to_groupid\":" + groupId + "}";
                            title = wxContent.getTitle();
                            hospitalImage = wxContent.getHospitalimage();
                            ToolUtils.getWechatInf(action, json);//更新分组

                            action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                            String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_EB;
		                    /* String url1=hostName+"index.html?viewType=1&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
		                	String url2=hostName+"index.html?viewType=2&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
		                    String url3=hostName+"index.html?viewType=3&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
		                 	String url4=hostName+"index.html?viewType=4&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;*/

                            json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
                                    "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
                                    "{\"title\":\"用户端APP下载\",\"description\":\"\",\"url\":\"" + appUrl + "\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/app.png\"}," +
		                 			/*"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
		                 			"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
		                 			"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+*/
                                    "]}}";
                            ToolUtils.getWechatInf(action, json);
                        } else if ("CLICK".equals(event)) {
                            String key = (String) wxData.get("EventKey");
                            if (("mfpc").equals(key)) {
                                String code = "";
                                String sdUrl = Constants.GET_USER_URL + accessToken + "&openid=" + fromUserName + "&lang=zh_CN";
                                String userStr = ToolUtils.getWechatInf(sdUrl, null);
                                JSONObject result = null;
                                if (userStr != null) {
                                    result = JSONObject.parseObject(userStr);
                                    Integer group = (Integer) result.get("groupid");
                                    if (group != null && group != 0) {
                                        code = group + "";
                                    } else {
                                        code = Constants.DEFAULT_GROUP_EBSF;
                                    }
                                }
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("groupId", code);
                                map.put("wechatCode", Constants.WECHAT_CHANNEL_EB);
                                BsWxContent wxContent = confCacheDao.selectWxContent(map);
                                if (null == wxContent) {
                                    logger.error("[" + code + "]对应二维码信息未配置，请联系系统管理员配置");
                                    return;
                                }
                                title = wxContent.getTitle();
                                hospitalImage = wxContent.getHospitalimage();
                                String url = hostName + "index.html?viewType=0&openId=" + fromUserName + "&code=" + wxContent.getCode() + "&wechatCode=" + Constants.WECHAT_CHANNEL_EB;
                                //String url1=hostName+"index.html?viewType=1&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
                                //String url2=hostName+"index.html?viewType=2&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
                                //String url3=hostName+"index.html?viewType=3&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;
                                //String url4=hostName+"index.html?viewType=4&openId="+fromUserName+"&code="+wxContent.getCode()+"&wechatCode="+Constants.WECHAT_CHANNEL_EB;

                                action = Constants.MESSAGE_CUSTOM_SEND + accessToken;
                                json = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"news\",\"news\":{\"articles\": [" +
                                        "{\"title\":\"" + title + "\",\"description\":\"\",\"url\":\"" + url + "\",\"picurl\":\"" + hospitalImage + "\"}," +
                                        "{\"title\":\"用户端APP下载\",\"description\":\"\",\"url\":\"" + appUrl + "\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/app.png\"}," +
                                        //"{\"title\":\"生长发育评测 \",\"description\":\"\",\"url\":\""+url2+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E7%94%9F%E9%95%BF%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
                                        //"{\"title\":\"智能发育评测 \",\"description\":\"\",\"url\":\""+url3+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E6%99%BA%E8%83%BD%E5%8F%91%E8%82%B2%E8%AF%84%E6%B5%8B1.png\"},"+
                                        //"{\"title\":\"养育环境评测 \",\"description\":\"\",\"url\":\""+url4+"\",\"picurl\":\"http://bbcare.oss-cn-hangzhou.aliyuncs.com/image/wx/%E5%85%BB%E8%82%B2%E7%8E%AF%E5%A2%83%E8%AF%84%E6%B5%8B.png\"},"+
                                        "]}}";
                                ToolUtils.getWechatInf(action, json);
                            }
                        }
                    }
                } else {
                    logger.info("echostr:::" + data.get("echostr"));
                    responseStr = (String) data.get("echostr");
                    response.getWriter().write(responseStr);
                }
            } else {
                logger.info("token check failed");
                responseStr = "Access Forbidden";
                response.getWriter().write(responseStr);
            }
        } catch (Exception e) {
            logger.error("wechatInitForEbsf Error {}", e);
        }
    }

    @RequestMapping("/wechatgetHospital")
    @ResponseBody
    public ResultModel<Object> wechatgetHospitalForLH(@RequestBody String arg, HttpServletRequest request) throws Exception{
        logger.info("in getMabcBasicInfo----arg==" + arg);

        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if(null == requestParam ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "无data节点！");
        }

        String openId = requestParam.getString("openId");
        if (org.springframework.util.StringUtils.isEmpty(openId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "openId不能为空！"));
        }

        Map<String, Object> wechatmap = confCacheDao.selectgroupIdByopenId(openId);
        String groupId = (String) wechatmap.get("groupId");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("wechatCode", Constants.WECHAT_CHANNEL_LH);
        map.put("groupId", groupId);

        Map<String, Object> resmap = weChatUserService.getWxContent(map);

        logger.info("out wechatgetHospitalForLH----arg==");
        return new ResultModel<Object>(resmap);
    }

}
